const config = require("./config");
const log = require("./log");
const dealRequest = require("./request");
const { loadCommClass } = require("./comm");
const { loadOrm } = require("./orm/load");
const { loadRedis } = require("./redis");
const { typings } = require("./typings");
const { loadPlugin } = require("./plugin");
const { loadTask, loadQueue, consume } = require("./task");
const lifecycle = require("./lifecycle");
const getValidPort = require("./port");
const loadEs = require("./es/load");
const { socketInit } = require("./socket");
const Koa = require("koa");
const app = new Koa();
async function young() {
  app.config = config;
  app.env = process.env.npm_lifecycle_event == "start" ? "prod" : "dev";
  app.log = log;
  //存放所有类
  app.service = {};
  //存放通用类
  app.comm = {};
  //启动配置
  if (lifecycle && lifecycle.before) lifecycle.before(app);
  //生成声明文件
  //处理组件
  loadPlugin(app);
  //处理请求
  dealRequest(app);
  typings();
  //加载数据库
  await loadOrm(app);
  //加载redis
  loadRedis(app);
  //加载通用函数
  loadCommClass(app);
  //加载任务
  loadTask(app);
  //加载队列
  loadQueue(app);
  //加载elasticsearch
  loadEs(app);
  const port = await getValidPort(app.config.port, app);
  //加载socket
  const socket = await socketInit(app);
  if (socket) {
    socket.listen(port, async () => {
      //队列消费
      consume(app);
      app.log.success(
        `server (with socket) start at: \x1B[4mhttp://localhost:${port}\x1B[0m\n`,
        true
      );
      //启动自定义
      if (lifecycle && lifecycle.ready) lifecycle.ready(app);
    });
  } else {
    app.listen(port, async () => {
      //队列消费
      consume(app);
      app.log.success(
        `server start at: \x1B[4mhttp://localhost:${port}\x1B[0m\n`,
        true
      );
      //启动自定义
      if (lifecycle && lifecycle.ready) lifecycle.ready(app);
    });
  }
  return app;
}
module.exports = young;
